package Ecu911_Interfaz;

import Ecu911_Excepciones.CedulaCorrecta;
import Ecu911_Excepciones.ExceptionSql;
import Ecu911_Excepciones.ValoresNulos;
import Ecu911_Negocio.NegUsuarios;
import java.awt.Color;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Random;
import java.util.TimerTask;
import javax.swing.JOptionPane;

/**
 *
 * @author Mrcelo Montaño
 */
public class FrmLogIn extends javax.swing.JDialog {

    NegUsuarios miUsuario = new NegUsuarios();
    boolean mensajeAdvertenciaActivo;
    
    
    /**
     * Creates new form FrmLogIn
     */
    public FrmLogIn(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
         this.getContentPane().setBackground(Color.white);
         this.mensajeAdvertenciaActivo = false;
    }
    
    private boolean validarCamposTextoCompleto(){
       boolean check = true;
       if(this.txtCedula.getText().compareTo("")==0 ||
          this.txtContraseña.getPassword().length==0){
           check = false;
       }
       return check;
   }
   
    private void pintarTextosVacios(){
       if(this.txtCedula.getText().compareTo("")==0){
           this.txtCedula.setBackground(Color.yellow);
       }
       else{
           this.txtCedula.setBackground(Color.white);
       }
       if(this.txtContraseña.getPassword().length==0){
           this.txtContraseña.setBackground(Color.yellow);
       }
       else{
           this.txtContraseña.setBackground(Color.white);
       } 
    }
    
    private void mensajeAdvertenciaVisibleOn(){
        this.jLabel2.setVisible(false);
    }
    
    private void mensajeAdvertenciaVisibleOff(){
        this.jLabel2.setVisible(true);
    }

    public class automatico extends Observable{
        public automatico(){
             java.util.Timer timer = new java.util.Timer();
             timer.scheduleAtFixedRate(timerTask, 10,300);
        }
        TimerTask timerTask = new TimerTask(){
             public void run() {
                        Color c = Color.RED;
                        Random rand = new Random();
                        int x = rand.nextInt(3) + 1;
                        switch (x) {
                            case 1 : c = Color.white;break;
                                                            
                        }
                        jLabel2.setForeground(c);
                        
                    }
        };
    }
    
    private boolean validarCedulaUsuario(String cedula){
       if(cedula.length()==10){
           boolean validacion = false, band = true;
           int suma = 0;
           int multiplicador = 2;
           ArrayList numeroDescompuesto = this.descomponerCadena(cedula);
           for(int i=0; i<numeroDescompuesto.size()-1; i++){
               int multiplicacion = (multiplicador * Integer.parseInt(numeroDescompuesto.get(i).toString()));
               if (multiplicacion>9){
                   multiplicacion = multiplicacion - 9;
               }
               suma = suma + multiplicacion;
               if (band){
                   multiplicador = 1;
                   band = false;
               }
               else{
                   multiplicador = 2;
                   band = true;
               }
           }
           suma = 10 - suma%10;
           int digitoPrueba = Integer.parseInt(numeroDescompuesto.get(9).toString());
           if (suma == digitoPrueba){
               validacion = true;
           }
           return validacion;
       }
       else{
           return false;
       }
   }
    
    private ArrayList descomponerCadena(String cadena){
       ArrayList cad = new ArrayList();
       for(int i=0; i<cadena.length(); i++){
           cad.add(cadena.substring(i, i+1));
       }
       return cad;
   }
   
   private void imprimirMensajeError(String msj){
       JOptionPane.showConfirmDialog(null,msj,
       "ERROR DE SISTEMA",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null); 
   }
   
   private void imprimirMensajeAcciónRealizada(String msj){
       JOptionPane.showConfirmDialog(null,msj,
       "ACCION DE SISTEMA",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
   }
   
   private void validarInformaciónNuevoRegistro(boolean val)throws ValoresNulos, CedulaCorrecta, ExceptionSql, SQLException{
        if (val){
            this.validarCedulaNuevoRegistro(this.validarCedulaUsuario(this.txtCedula.getText()));
        }
        else{
            this.pintarTextosVacios();
            throw new ValoresNulos();
        }
    }
    
    private void validarCedulaNuevoRegistro(boolean val)throws CedulaCorrecta, ExceptionSql, SQLException{
       if(val){
           this.usuarioExistencia();
       }
       else{
           this.pintarTextosVacios();
           throw new CedulaCorrecta();
       }       
    }
    
    private void usuarioExistencia(){
        miUsuario.setIdUsuario(this.txtCedula.getText());
        if (miUsuario.cargarMiUsuarioDB()!=null){
            //HAGO EL LOGEO
            String password = new String(txtContraseña.getPassword());
            if(miUsuario.getPasUsuario().compareTo(password)==0){
                this.imprimirMensajeAcciónRealizada("Información correcta. \nUsuario: \n"+
                                                    miUsuario.getNomUsuario() + " " + miUsuario.getApeUsuario());
                this.mensajeAdvertenciaVisibleOn();
                FrmPrincipal.idUsuarioActivo = miUsuario.getIdUsuario();
                this.dispose();
            }
            else{
                if (!this.mensajeAdvertenciaActivo){
                    this.mensajeAdvertenciaVisibleOff();
                } 
            }
        }
        else{
            this.imprimirMensajeError("Error en la búsqueda. \nEl usuario no está registrado.");
            this.pintarTextosVacios();
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtCedula = new javax.swing.JTextField();
        txtContraseña = new javax.swing.JPasswordField();
        btnIngresar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ECU911 - [LogIn de Usuario]");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Candado.png"))); // NOI18N

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("Usuario:");

        jLabel4.setText("Contraseña:");

        txtContraseña.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtContraseñaKeyPressed(evt);
            }
        });

        btnIngresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/LlaveIngresar.png"))); // NOI18N
        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnIngresar)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtCedula, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtContraseña, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnIngresar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");

        jLabel2.setForeground(new java.awt.Color(153, 0, 0));
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/BotonInactivo.png"))); // NOI18N
        jLabel2.setText("Datos incorrectos.");

        jPanel2.setBackground(new java.awt.Color(255, 102, 0));

        jLabel6.setForeground(new java.awt.Color(255, 255, 255));
        jLabel6.setText("Verificar usuario y sistema.");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnCancelar))
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 20, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(btnCancelar))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        // TODO add your handling code here:
        try{
            this.validarInformaciónNuevoRegistro(this.validarCamposTextoCompleto());
        } 
        catch(ValoresNulos e){
            this.imprimirMensajeError(e.getMessage());
        }
        catch(CedulaCorrecta e){
            this.imprimirMensajeError(e.getMessage());
        }
        catch(SQLException e){
            this.imprimirMensajeError(e.getMessage());
        }  
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        this.mensajeAdvertenciaVisibleOn();
        new automatico();
    }//GEN-LAST:event_formWindowOpened

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
              
    }//GEN-LAST:event_formKeyPressed

    private void txtContraseñaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContraseñaKeyPressed
        if(evt.getKeyCode()==10){
            try{
                this.validarInformaciónNuevoRegistro(this.validarCamposTextoCompleto());
            } 
            catch(ValoresNulos e){
                this.imprimirMensajeError(e.getMessage());
            }
            catch(CedulaCorrecta e){
                this.imprimirMensajeError(e.getMessage());
            }
            catch(SQLException e){
                this.imprimirMensajeError(e.getMessage());
            }   
        }  
    }//GEN-LAST:event_txtContraseñaKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmLogIn dialog = new FrmLogIn(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JPasswordField txtContraseña;
    // End of variables declaration//GEN-END:variables
}
